/**
 * Manage an controlled history for a webapp
 * Can Work with jQuery Mobile
 *
 * Data are persistent and stored in localStorage
 * @author Naxan
 */
 
var WebappHistory = new (function() {
	
	var history = [];
	var $this = this;
	
	/**
	 * Push a page in history
	 */
	this.push = function(p) {
		if (!p) {
			p = window.location.href;
		}
		history.push(p);
		save();
	}
	
	/**
	 * Return the last page stored in history
	 */
	this.back = function() {
		var p = history.pop();
		save();
		return p;
	}
	
	/**
	 * Clean the history
	 */
	this.clean = function() {
		history = [];
		save();
	}
	
	/**
	 * Initialization
	 */
	this.init = function() {
		load();
		$("body").on("pagebeforeshow", ".ui-page", onPageChangeJQM);
		$("body").on("click", ".webapphistory-back-link-jqm", onClickBackJQM);
		$("body").on("click", ".webapphistory-link", onClickLinkHistory);
	}

	/**
	 * Load the history in localStorage
	 */
	function load() {
		history = [];
		if (localStorage["webapphistory_history"]) {
			history = JSON.parse(localStorage["webapphistory_history"]);
		}
	}
	
	/**
	 * Save the history in localStorage
	 */
	function save() {
		localStorage["webapphistory_history"] = JSON.stringify(history);
	}
	
	/**
	 * For JQuery Mobile Only
	 * Show the back button if there are history
	 * Must be called manually
	 */
	this.loadBackButtonJQM = function(page) {
		var btn = $(page).find(".webapphistory-back-link-jqm");
		
		if (history.length) {
			btn.css("display", "block");
		}
		else {
			btn.css("display", "none");
		}
	}
	
	/**
	 * For JQuery Mobile Only
	 * Event fired when user click on back button
	 * Change the page with the transition data on the link
	 */
	function onClickBackJQM() {
		var p = $this.back();
		var transition = $(this).attr("data-transition");
		$.mobile.changePage(p, {transition: transition, reverse: true});
	}
	
	/**
	 * For JQuery Mobile Only
	 * Event fired when user click on back button
	 * Change the page with the transition data on the link
	 */
	function onClickLinkHistory() {
		var link = $(this);
		if (link.attr("webapphistory-page")) {
			$this.push(link.attr("webapphistory-page"));
		}
		else {
			$this.push();
		}
	}	
	
	/**
	 * For Jquery Mobile Only
	 * Event fired when a page change
	 * Add the back button
	 */
	function onPageChangeJQM() {
		var p = $(this);
		$this.loadBackButtonJQM(p);
	}
	
	$(document).ready(this.init);
});